package com.winning.pmph.vo;

import com.alibaba.fastjson.JSON;
import com.winning.pmph.entity.Knowledge;
import com.winning.pmph.entity.KnowledgeField;
import com.winning.pmph.entity.ReleasedKnowledgeField;
import com.winning.pmph.service.ReleasedKnowledgeFieldService;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.Const;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.util.List;
import java.util.stream.Collectors;

@Data
@Document(indexName = "knowledge", type = "knowledge")
public class EsKnowledge {
    @Id
    private String id;
    @Field(type = FieldType.Keyword)
    private String name;
    @Field(type = FieldType.Keyword)
    private String knowledgeLibId;
    @Field(type = FieldType.Keyword)
    private String knowledgeLibName;
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String content;

    public static EsKnowledge parse2EsKnowledge(Knowledge knowledge) {
        EsKnowledge esKnowledge = new EsKnowledge();
        esKnowledge.setId(knowledge.getId());
        esKnowledge.setName(knowledge.getName());
        esKnowledge.setKnowledgeLibId(knowledge.getKnowledgeLibId());
        if (CollectionUtils.isEmpty(knowledge.getKnowledgeFieldList())) {
            List<ReleasedKnowledgeField> releasedKnowledgeFields = ApplicationContextUtil.getBean(ReleasedKnowledgeFieldService.class)
                    .lambdaQuery()
                    .eq(ReleasedKnowledgeField::getKnowledgeId, knowledge.getId())
                    .eq(ReleasedKnowledgeField::getHidden, 0).list();
            knowledge.setKnowledgeFieldList(JSON.parseArray(JSON.toJSONString(releasedKnowledgeFields), KnowledgeField.class));
        }
        String content = knowledge.getKnowledgeFieldList().stream()
                .filter(field -> !StringUtils.equals(field.getProperty(),
                        Const.KNOWLEDGE_FIELD_VALUE_DEFAULT.get(field.getKind())))
                .filter(field -> Const.ES_KNOWLEDGE_FIELD_TYPE_ARRAY.contains(field.getKind()))
                .map(KnowledgeField::getProperty)
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.joining(System.lineSeparator()));
        esKnowledge.setContent(content);
        return esKnowledge;
    }
}
